-- WaitAndLoadingM
-- Created by panyl 31/Aug/2016
-- 等待加载机制

module("WaitAndLoadingM", package.seeall);

local msg_wait_map = {};
local waiting = {};

local whenMessageDone = nil;
local whenSendMessage = nil;

-- 初始化
function init()
    msg_wait_map = {};
    waiting = {};

    -- 转换下bine信息表
    local pend_message_CSV = get_pend_message_CSV();
    for i = 1, #pend_message_CSV do
        msg_wait_map[pend_message_CSV[i].msg_no] = pend_message_CSV[i];
    end

    pend_message_CSV = {};

    -- 等消息
    EventMgr.removeAll("WaitAndLoadingM");
    EventMgr.register("WaitAndLoadingM", event.MESSAGE_DONE, whenMessageDone);

    EventMgr.register("WaitAndLoadingM", event.SEND_MESSAGE, whenSendMessage);
end

function wait(msg, timeout)
    do return end
end

whenMessageDone = function(para)
    local msg_no = MSG.getMsgId(para[1]);

    if waiting[msg_no] then
        EventMgr.fire(event.CLOSE_WAIT_LOADING);
    end

    waiting[msg_no] = nil;

    if waiting[0] then
        EventMgr.fire(event.CLOSE_WAIT_LOADING);
    end

    waiting[0] = nil;
end


whenSendMessage = function(para)
    local msg_no = para["msg_no"];
    local row = msg_wait_map[msg_no];
    if not row then
        return;
    end

    local msg = iif(type(row["focus_msg"]) == "number", row["focus_msg"], 0);
    local timeout = iif(type(row["timeout"]) == "number", row["timeout"], 15);

    if timeout <= 0 then
        return;
    end

    -- 先抛出等待中
    EventMgr.fire(event.WAIT_LOADING);

    waiting[msg] = true;

    -- 定时处理
    ScheduleM.createScheme("WaitAndLoadingM" .. msg, function()
        if waiting[msg] then
            EventMgr.fire(event.CLOSE_WAIT_LOADING);
        end

        waiting[msg] = nil;
    end, timeout, false);
end
